package jmars.mobile.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import jmars.mobile.common.Investigator;
import jmars.mobile.common.PropertiesLoader;
import jmars.mobile.datainvestigation.Summary;

/**
 * 
 * 
 * @author Jan
 *
 */
public class TimeSequenceMatrix implements Investigator {

	@Override
	public Long compute(File[] files, FileWriter writer) throws IOException, ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(Summary.dateFormat);
		Date begin = sdf.parse(PropertiesLoader.getProperty("time.beginDate"));
		Date end = sdf.parse(PropertiesLoader.getProperty("time.endDate"));
		Long interval = (long) (Double.parseDouble(PropertiesLoader.getProperty("time.intervalMinutes"))*60000);
		
		Long total = 0L;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		Map<Long,Map<String,Long>> results=new HashMap<Long,Map<String,Long>>();
		for(Long l=begin.getTime()-begin.getTime()%interval;l<=end.getTime();l=l+interval)
			results.put(l, new HashMap<String,Long>());
		DecimalFormat df = new DecimalFormat();
		df.applyPattern("0");
		Date tempBegin,tempEnd;
		Long tempBL,tempEL;
		Long segBL,segEL;
		String groupKey;
		Set<String> groupKeys=new HashSet<String>();
		boolean groupFlag=(Summary.groupColumns!=null&&!"".equals(Summary.groupColumns));
		for(File inputFile:files){
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			while((row=reader.readLine())!=null){
				cols=row.split(Summary.columnSeperator);
				if(Summary.filterRow(cols,true,false)) continue;
				
				groupKey="";
				if(groupFlag)
					for(Integer idx:Summary.groupColumnIdx)
						if(idx<cols.length)
							groupKey=groupKey+"$_$"+cols[idx]+"$_$";
						else groupKey=groupKey+"$_$$_$";
				if(!groupKeys.contains(groupKey))groupKeys.add(groupKey);
				tempBegin=sdf.parse(cols[5]);
				tempEnd=sdf.parse(cols[6]);
				tempBL=0L;tempEL=0L;segBL=0L;segEL=0L;
				if(tempBegin.getTime()<begin.getTime())
					tempBL=begin.getTime();
				else
					tempBL=tempBegin.getTime();
				if(tempEnd.getTime()<end.getTime())
					tempEL=tempEnd.getTime();
				else
					tempEL=end.getTime();
				if(tempEL<tempBL)
					continue;
				for(Long ll=tempBL-tempBL%interval;ll<=tempEL-tempEL%interval;ll=ll+interval){
					if(tempBL<ll) segBL=ll;
					else segBL=tempBL;
					if(ll+interval<tempEL) segEL=ll+interval;
					else segEL=tempEL;
					if(tempBL.equals(tempEL)){
						if(results.get(ll).containsKey(groupKey))
							results.get(ll).put(groupKey, results.get(ll).get(groupKey)+Long.parseLong(cols[10]));
						else{
							results.get(ll).put(groupKey, Long.parseLong(cols[10]));
						}
					}else{
						if(results.get(ll).containsKey(groupKey))
							results.get(ll).put(groupKey, results.get(ll).get(groupKey)+Long.parseLong(cols[10])*
									(segEL-segBL)/(tempEnd.getTime()-tempBegin.getTime()));
						else{
							results.get(ll).put(groupKey, Long.parseLong(cols[10])*(segEL-segBL)/(tempEnd.getTime()-tempBegin.getTime()));
						}
					}

				}
				total++;
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		writer.write("%need to be transposed.\r\n");
		writer.write("%total:"+df.format(total)+"\r\n");
		writer.write("%temporal count:"+results.size()+"\r\n");
		writer.write("%begin: "+sdf.format(begin)+"\r\n");
		writer.write("%end: "+sdf.format(end)+"\r\n");
		writer.write("%*****************details******************\r\n");
		writer.write("%rows:\r\n");
		for(String gk:groupKeys){
			writer.write("%"+gk.replaceAll("\\$_\\$\\$_\\$", ",").replaceAll("\\$_\\$","")+"\r\n");
		}

		writer.write("%columns:");
		for(Long l=begin.getTime()-begin.getTime()%interval;l<end.getTime();l=l+interval){
			writer.write(l+",");
		}
		writer.write("\r\n");
		
	    for(String gk:groupKeys){
	    	for(Long l=begin.getTime()-begin.getTime()%interval;l<end.getTime();l=l+interval){
	    		writer.write(results.get(l).get(gk)==null?"0":df.format(results.get(l).get(gk)));
	    		if(l+interval<end.getTime())writer.write(",");
	    	}
	    	writer.write("\r\n");
	    }
		return total;
	}

}
